import datetime
import md5
import time
import webbrowser
from requestor import Requestor
from amara import bindery

class LastFmApi():
    def __init__(self, apikey, secret, user, password):
        self._apikey = apikey
        self._secret = secret
        self._user = user
        self._password = password
        self._sk = None
        self._requestor = Requestor("https://ws.audioscrobbler.com/2.0/?")
        
    def Authenticate(self):
        webbrowser.open("http://www.last.fm/api/auth/?api_key=%s&token=%s" % (self._apikey, self.GetToken()))
        
    def GetInfo(self, user=None):
        '''
        Return dictionary of profile info of the given user, 
        or the currently authenticated user if no user provided
        '''
        
        args = {"method" : "user.getinfo"}
        if user:
            args["user"] = user
        else:
            args["user"] = self._user
        
        response = bindery.parse(self.GetResponse(args))
        self._userdata = response.lfm.user
#        for image in self._userdata.image:
#            print image.xml_properties, image
            
    def GetMethodSig(self, args):
        sigstring = ""
        args["api_key"] = self._apikey
        for arg in sorted(args.iterkeys()):
            print arg, args[arg]
            sigstring += arg + args[arg]
        sigstring += self._secret
        
        return md5.md5(sigstring).hexdigest()
        
    def GetRecentTracks(self, user=None, limit=None, page=None):
        '''
        Get dictionary of recently played track data for given user, or current user if not supplied
        Limit is the number of results per page, page is the page number to retrieve
        '''
        
        args = {"method": "user.getrecenttracks"}
        args["user"] = user or self._user
        if limit: args["limit"] = limit
        if page: args["page"] = page
            
        response = bindery.parse(self.GetResponse(args))
        self._recenttracks = response.lfm.recenttracks
        
    def GetResponse(self, args):
        args["api_key"] = self._apikey
        
        return self._requestor.DoRequest(args)
    
    def GetSession(self):
        args = {"method" : "auth.getMobileSession",
                "username": self._user,
                "password": self._password,
                "api_key": self._apikey}
        args["api_sig"] = self.GetMethodSig(args)
        
        response = self._requestor.DoPost(args)
        self._sk = str(bindery.parse(response).lfm.session.key)
    
    def GetToken(self):
        args = {"method" : "auth.gettoken"}
        args["api_sig"] = self.GetMethodSig(args)
        
        response = bindery.parse(self.GetResponse(args))
        return response.lfm.token
    
    def ScrobbleTrack(self, track):
        ''' Scrobble a single track to the authenticated account '''
        
        self.GetSession()
        
        args = {"method": "track.scrobble",
                "api_key": self._apikey,
                "sk": self._sk,
                "artist": track["artist"],
                "track": track["track"],
                "timestamp": str(int(time.mktime(datetime.datetime.now().timetuple())))}
        args["api_sig"] = self.GetMethodSig(args)
        
        response = self._requestor.DoPost(args)
        print response
        
    
    def ScrobbleTracks(self, tracks):
        ''' Scrobble all tracks in iterable tracks '''
        
        for track in tracks:
            print track
